<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
import {ref, computed, unref, reactive, nextTick} from 'vue';
import { message } from "ant-design-vue";
import { BasicDrawer, useDrawerInner, BasicForm, useForm } from '@gui-pkg/antdcomponents';
import {directSendMsg} from '@/api/alerts/warningSendRecords';
import {getAllStationData, getStationTreeData} from "@/api/information/rain";
import moment from 'moment';
import {getDeptTreeSelect} from "@/api/system/dept";

const townData = [
  {value: '大金镇', label: '大金镇'},
  {value: '四望镇', label: '四望镇'},
  {value: '梅川镇', label: '梅川镇'},
  {value: '花桥镇', label: '花桥镇'},
  {value: '田家镇街道', label: '田家镇街道'},
  {value: '余川镇', label: '余川镇'},
  {value: '大法寺镇', label: '大法寺镇'},
  {value: '刊江街道', label: '刊江街道'},
]
const LOGIN_USER_INFO_KEY: any = window.localStorage.getItem('LOGIN_USER_INFO_KEY');
const userData = JSON.parse(LOGIN_USER_INFO_KEY);

const isUpdate = ref(true);
const emit = defineEmits(['success', 'register']);
const configId = ref('');
const typeData = [{value: "1", label: '短信'}, {value: "2", label: '电话语音'}]
const statusData = [
  {value: "1", label: '极高风险'},
  {value: "2", label: '高风险'},
]
const warntypeData = [
  {value: "1", label: '站点预警'},
  {value: "2", label: '叫应预警'},
]
const templateData = [
  {value: "1", label: '气象预警'},
  {value: "2", label: '湖北防汛'},
]
const isWarntyp1 = (methodType: string) => methodType === '1';
// 存储动态获取的村数据
const villageOptions = ref<any[]>([]);

// 存储完整的树数据，用于查找子节点
const fullTreeData = ref<any[]>([]);

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, resetSchema }] = useForm({
  labelWidth: 100,
  schemas: [
    {
      field: 'methodType',
      label: '预警类型',
      component: 'RadioButtonGroup',
      defaultValue: '1',
      componentProps: {
        options: warntypeData,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      field: 'types',
      label: '通知方式',
      component: 'Select',
      required:true,
      componentProps: {
        options: typeData,
        mode: "multiple",
      },
    },
    {
      field: "warnLevel",
      label: '预警等级',
      component: "Select",
      required:true,
      componentProps: {
        options: statusData,
        onChange: (v: any) => {
          console.log('预警等级变化:', v)
          state.selectedContent = v;
          if(v == 1  ){
            state.selectedContent = '根据实时降雨监测数据分析，{发生时间}，{发生地点}累计降雨超预警值，致灾风险极高，请特别加强防范，做好群众转移避险工作。'
          } else{
            state.selectedContent = '根据实时降雨监测数据分析，{发生时间}，{发生地点}累计降雨超预警值，致灾风险较高，请注意防范，做好群众转移避险准备工作。'
          }
          setFieldsValue({
            "msgContent": state.selectedContent
          });
        },
      },
      ifShow: ({ values }) => isWarntyp1(values.methodType),
    },

    {
      label: '站点信息（村）',
      field: 'targets',
      component: 'ApiTreeSelect',
      required: true,
      componentProps: () => {
        return {
          api: () => new Promise((resolve) => {
            getStationTreeData({"town":
                ( userData.roles.includes("admin") || userData.roles.includes("city_role"))?"":userData.deptName
            }).then((res:any) => {
              console.log('-------',res);
              // 保存完整的树数据
              fullTreeData.value = res;
              // 处理数据，禁用一级节点（镇节点）
              const processedData = processTreeData(res);
              resolve(processedData);
            });
          }),
          multiple: true, // 启用多选
          fieldNames: {
            label: 'label',
            key: 'id',
            value: 'id',
          },
          // 添加禁止选择非叶子节点的配置
          treeCheckable: true,
          treeCheckStrictly: false, // 关闭严格选择模式，实现父子联动
          showCheckedStrategy: 'SHOW_ALL', // 显示所有选中的节点
          // 自定义节点选择逻辑
          onSelect: (selectedKeys: any, {node}: any) => {
            // 禁止选择非叶子节点（镇节点）
            if (node.children && node.children.length > 0) {
              return false;
            }
          },
          // 自定义节点勾选逻辑 - 选中镇节点时自动选中所有子节点
          onCheck: (checkedKeys: any, {node, checked}: any) => {
            // 如果是镇节点被选中，自动选中所有子节点
            if (node.children && node.children.length > 0 && checked) {
              const allChildKeys = getAllChildKeys(node);
              const newCheckedKeys = [...new Set([...checkedKeys.checked, ...allChildKeys])];

              // 更新选中值
              setTimeout(() => {
                setFieldsValue({
                  targets: newCheckedKeys
                });
              }, 0);
            }

            // 如果是镇节点被取消选中，自动取消所有子节点
            if (node.children && node.children.length > 0 && !checked) {
              const allChildKeys = getAllChildKeys(node);
              const newCheckedKeys = checkedKeys.checked.filter((key: string) => !allChildKeys.includes(key));

              // 更新选中值
              setTimeout(() => {
                setFieldsValue({
                  targets: newCheckedKeys
                });
              }, 0);
            }
          },
        };
      },
    },
    {
      field: 'startTime',
      component: 'DatePicker',
      label: '预警发生时间',
      required: true,
      ifShow: ({ values }) => isWarntyp1(values.methodType),
      defaultValue: new Date(), // 设置默认值为当前时间
      componentProps: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        showTime: true,
        disabledDate: (current: any) => {
          // 禁用今天之前的所有日期
          return current && current < moment().startOf('day');
        },
        disabledTime: (current: any) => {
          if (!current) {
            return {};
          }

          const now = moment();
          const selectedDate = moment(current);

          // 如果是今天，禁用当前时间之前的小时和分钟
          if (selectedDate.isSame(now, 'day')) {
            return {
              disabledHours: () => {
                const hours = [];
                for (let i = 0; i < now.hour(); i++) {
                  hours.push(i);
                }
                return hours;
              },
              disabledMinutes: (selectedHour: number) => {
                if (selectedHour === now.hour()) {
                  const minutes = [];
                  for (let i = 0; i < now.minute(); i++) {
                    minutes.push(i);
                  }
                  return minutes;
                }
                return [];
              },
              disabledSeconds: (selectedHour: number, selectedMinute: number) => {
                if (selectedHour === now.hour() && selectedMinute === now.minute()) {
                  const seconds = [];
                  for (let i = 0; i < now.second(); i++) {
                    seconds.push(i);
                  }
                  return seconds;
                }
                return [];
              },
            };
          }

          return {};
        },
      },
    },
    {
      field: 'msgContent',
      label: '发送内容',
      component: 'InputTextArea',
      componentProps: {
        rows: 10,
        disabled:true,
      },
      required:true,
      ifShow: ({ values }) => isWarntyp1(values.methodType),
    },

    {
      field: "templateType",
      label: '预警模板',
      component: "Select",
      required:true,
      componentProps: {
        options: templateData,
        onChange: (v: any) => {
          console.log('预警模板变化:', v)
          if(v=='1'){
            state.selectedTemplateContent = 'XX气象台XX年XX月XX日XX时XX分发布XX预警信号：预计XX时，武穴部分乡镇（街道）将出现XX降雨，最大小时雨强XX毫米，伴有XX强降水，山区山洪、地质灾害、中小河流洪水、城乡积涝风险高，请加强防范。';
          }else{
            state.selectedTemplateContent = 'XX镇街XX等村超警，XX自动站(XX:XX)XX小时雨量XX毫米,超警戒雨量值(XX毫米)XX毫米，请做好XX防范应对工作!';
          }

          setFieldsValue({
            "msgContent2": state.selectedTemplateContent
          });
        },
      },
      ifShow: ({ values }) => !isWarntyp1(values.methodType),
    },
    {
      field: 'msgContent2',
      label: '发送内容',
      component: 'InputTextArea',
      componentProps: {
        rows: 10,
      },
      required:true,
      ifShow: ({ values }) => !isWarntyp1(values.methodType),
    },
  ],
  showActionButtonGroup: false,
  baseColProps: {span: 24 },
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
  } else {
  }
});

// 获取节点的所有子节点key
const getAllChildKeys = (node: any): string[] => {
  let keys: string[] = [];

  if (node.children && node.children.length > 0) {
    node.children.forEach((child: any) => {
      // 如果是叶子节点，添加到keys
      if (!child.children || child.children.length === 0) {
        keys.push(child.id);
      } else {
        // 递归获取子节点的子节点
        keys = [...keys, ...getAllChildKeys(child)];
      }
    });
  }

  return keys;
};

// 添加处理树数据的函数
const processTreeData = (data: any[]) => {
  return data.map(item => {
    // 复制对象，避免修改原始数据
    const processedItem = {...item};

    // 如果节点有子节点（是镇节点），则禁用选择
    if (processedItem.children && processedItem.children.length > 0) {
      //processedItem.disabled = true;
      // 递归处理子节点
      processedItem.children = processTreeData(processedItem.children);
    }

    return processedItem;
  });
};

const state = reactive({
  name: 'vue3',
  selectedContent: "",
  selectedTemplateContent: "",
  town:"",
});

const getTitle = computed(() => (!unref(isUpdate) ? '发送' : '编辑配置'));

async function handleSubmit() {
  try {
    const values = await validate();
    const methodType = values.methodType;
    if(methodType=='2'){
      const msgContent = values.msgContent2;
      if(msgContent.indexOf("X")>-1){
        message.error("根据工信部要求，发送内容存在敏感字符，请调整发送内容");
        return ;
      }
    }

    setDrawerProps({ confirmLoading: true });

    await directSendMsg(values);
    message.success('发送成功');

    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
</style>
